<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>修德抄经堂</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<link rel="stylesheet" type="text/css" href="../bower_components/mui/dist/css/mui.min.css">
	<link rel="stylesheet" type="text/css" href="../css/base.css">
    <link rel="stylesheet" type="text/css" href="../css/a1.css">
	<link rel="stylesheet" type="text/css" href="../css/full.css">
	<link rel="stylesheet" type="text/css" href="../css/chaoxieer.css">
	<script src="../bower_components/jquery/dist/jquery.js"></script>
</head>
<body>
    <div id="mcover" style="display:none;">
          <img src="../img/guide.png" />
        </div>
	<div id="mcover1">
		<div>
			<div id="xian">
				<p>抄写失败，请重试！</p>
				<button>确定</button>
			</div>
		</div>
	</div>
	<div id="mcover3"></div>
<canvas id="canvasId"  style="z-index: 1000"></canvas>
	<div class="page">
		<!--<header class="mui-bar mui-bar-nav title">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"><span>返回</span></a>
	      	<h1 class="mui-title">道德抄经堂</h1>
	    </header>-->
	    <div class="content">
            <div class="words_backgroud">
                <div class="fojing_pic">
                    
                </div>
	    		<!--<img src="../img/write/demo.png" class="cover">-->
	    	</div>
	    	<div class="write">
	    		<div class="write_detail">
	    			<div class="write_left">
	    				<!--<img src="../img/write/text.png">-->

	    			</div>
	    			<div id="write_right_panel" class="write_right write_right_embg">
	    				<div class="all_tin">
	    					<div class="tin">
	    						<img src="../img/write/ture.png" class="cover" id="commit">
	    					</div>
	    					<div class="tin false">
	    						<img src="../img/write/flase.png" class="cover" id="clear">
	    					</div>
	    				</div>
	    			</div>
	    			<div class="tanchukuang" style="display: none;">
	    				<ul class="btn">
			            	<a href="#" id="fenxiang"><li>
			            		<img src="../img/benxin/write.png">
			            		<p class="same">邀请</p>
			            	</li></a>
			            	<a href="#" id="read"><li>
			            		<img src="../img/benxin/read.png">
			            		<p class="same">阅读</p>
			            	</li></a>
                            <a href="#" id="exit"><li>
			            		<img src="../img/benxin/exit.png">
			            		<p class="same">退出</p>
			            	</li></a>
		            	</ul>
	    			</div>
	    		</div>
	    		<div class="bottom">
	    			<div class="border_left">

	    				<div class="core">
	    					<img src="../img/write/core.png" class="cover">
	    				</div>
	    			</div>
	    			<div class="border_right" >
	    				<img src="../img/write/more.png">
	    			</div>
	    		</div>
	    	</div>
	    </div>
	</div>
</body>
<script src="../bower_components/mui/dist/js/mui.min.js"></script>
<script src="../js/common.js"></script>
<script src="../js/handwriting.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

<script>
	$('#read').click(function () {
		location.href = "read_jingjin.html?id="+ versionId;
    })
</script>
<script>
	$(function(){
        var csrftoken = getCookie('csrftoken');
        function commitCopyIndex(UTSID, PageNum, charIndex) {
            // 提交抄写进度
            // UTSID: userTranscriptionID
            var api = '/fe/transcript/user_transcription/';
            api = api + UTSID + '/pages/' + PageNum + '/chars/' + charIndex;
            $.ajax({
                url: api,
                type: 'POST',
                async: false,
                beforeSend: function(xhr, settings) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                },
                success: function(data) {
                    console.log('commit success');
                },
            })
        }


        function WordImgUpload(Base64Img, n_w, hwStroke, a){
            var img = Base64Img.split(';base64,');
            var csrftoken = getCookie('csrftoken');
            var res = false;
            data = {
                'base64img': img[1],
                'r_txt': n_w,
                'hw_stroke': hwStroke,
                'a': a,
            }
            $.ajax({
                url: '/fe/imgrecog/word',
                type: 'POST',
                data: data,
                async: false,
                dataType: 'json',
                beforeSend: function(xhr, settings) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                },
                success: function(data, status){
                    if(data.status == 403){
                        self.location='login.html'; 
                        return
                    }
                    if(data.status == 200){
                        if(data.data.recg){
                            res = true;
                        }
                    }
                },
            });
            return res
        }


		$(".border_right").click(function(){
            $(".border_right").css("display","none");
			$(".tanchukuang").toggle();
			var write_right_panel=$("#write_right_panel");

			if(write_right_panel.hasClass("write_right_embg")){
			}else{
				write_right_panel.addClass("write_right_embg");
			}
			$('#mcover3').show();
		});


		//获取抄写页进度
		var vId = localStorage.getItem('versionId');
        var startWordIndex = 0;
        var startForIndex = 0;
        var pageNum = null;
        var pageTotal = null;
        var surplusWordNum = 0;
        var backgroundUrl = '../img/write/demo1.png';
        var fontColor = '#080808';
        var words = new Array();
        var hd = 'zh-cn';
		var userTranscriptionID = localStorage.getItem('userTranscriptionID');
		ajax('/fe/transcript/user_transcription/'+userTranscriptionID+'/progress',null).then(
            function (data) {
                if(data.status=='410'){
                     alert('已抄完');
                     location.href = 'jingjin.html'
                };
                var data = data.data;
                startWordIndex = data.char_index;
                pageNum = data.page_num;
                pageTotal = data.total_page_num;
                page_total_char_num = data.page_total_char_num;
                if(data.layout_config){
                    if (data.layout_config.material_url) {
                        backgroundUrl = data.layout_config.material_url;
                    }
                    img_url = 'url(' + backgroundUrl + ')';
                    $('.words_backgroud').css("background-image", img_url);
                    fontColor = data.layout_config.font_color;
                    localStorage.setItem('fontColor',fontColor);
                }
                return ajax('/fe/transcript/sutra_edition/'+vId+'/pages/'+data.page_num+'',null);
            }
		).then(function (data) {
		   var data = data.data.chars;
		   var text = '';
		   var left = $('.border_left');
           a = '-webkit-backdrop-filter: drop-shadow('+fontColor+' 100px 0px);'
            a = a+'-moz-filter: drop-shadow('+fontColor+' 100px 0px);'
            a = a+'-webkit-filter: drop-shadow('+fontColor+' 100px 0px);'
            a = a+'-o-filter: drop-shadow('+fontColor+' 100px 0px);'
            a = a+'filter: drop-shadow('+fontColor+' 100px 0px);'
            a = a+'-ms-filter: drop-shadow('+fontColor+' 100px 0px);'
		   for(var i = 0,len = data.length;i<len;i++) {
                if (data[i].index < startWordIndex) {
                    // $('.fojing_pic').append('<div class="word-frmame"><img class="word-show" src="'+data[i].img_url+'"></div>');
                    $('.fojing_pic').append('<div class="icon word-frmame show"><div class="icon word-show" style="' + a +'background: url('+ data[i].img_url +') no-repeat center;background-size: contain"></div></div>');
                    startForIndex = i + 1;
                }else {
                    // $('.fojing_pic').append('<div class="word-frmame"><img class="word-hide" src="'+data[i].img_url+'" data-index="' + data[i].index +'"></div>');
                    $('.fojing_pic').append('<div class="icon word-frmame show"><div class="icon word-hide" data-index="'+data[i].index+'" style="'+a+'background: url('+ data[i].img_url +') no-repeat center;background-size: contain"></div></div>');
                    text += '<span>'+data[i].text+'</span>';
                    words.push(data[i].text)
                    surplusWordNum++;
                }
		   }
            if (startForIndex >= data.length){
                if(pageNum == pageTotal)location.href = 'zhuchaoren.html?id='+userTranscriptionID;
            }
            left.append(text);
		   //点击确定
			var index = startForIndex;
            var copiedNum = 0;
            var nowWord;
            $('#commit').click(function () {
                var canvas = document.getElementById('canvasId');
				if(hw.isCanvasBlank(canvas)) {
				    return;
				}else {
                    console.log(words[copiedNum])
                    res = hw.createImg(words[copiedNum]);
                    if (!res) {
                        $("#mcover1").css("display","block");
                        return
                    }
				    hw.clear();
                    img = $('.word-frmame').find('div').eq(index);
                    img.removeClass('word-hide');
                    img.addClass('word-show');
                    $('.border_left').find('span').eq(0).remove();
                    // 提交重写进度
                    commitCopyIndex(userTranscriptionID, pageNum, img.data("index"));
                    copiedNum++;
                    if (copiedNum >= surplusWordNum){
                        if(pageNum == pageTotal){
                            location.href = 'zhuchaoren.html?id='+userTranscriptionID;
                        }
                        else {
                            pageNum++;
                            location.reload();
						}
					}
					index++;
				};
            });
            //点击取消
			$('#clear').click(function () {
				hw.clear();
            })
        }).then(function () {

        })
		//抄写
		var width = $('.write_left').width(),
			height = $('.write_left').height(),
			canvas = $('#canvasId');
		canvas.attr('width',width);
		canvas.attr('height',height);
		canvas.click(function (e) {
			console.log(e.target);
        });
        function Handwriting(id) {
            this.canvas = document.getElementById(id);
            this.ctx = this.canvas.getContext("2d");
			console.log(this.ctx)
            // this.ctx.fillStyle = "rgba(0,0,0,0.5)";
            // console.log(fontColor)
            this.ctx.fillStyle = localStorage.getItem('fontColor');
            this.canvas.addEventListener("touchstart", this.downEvent.bind(this), false);
            this.canvas.addEventListener("touchmove", this.moveEvent.bind(this), false);
            this.canvas.addEventListener("touchend", this.upEvent.bind(this), false);
            this.canvas.addEventListener("contextmenu", function(e){ e.preventDefault() }, false);
            //this.canvas.onmousedown = this.downEvent.bind(this);
            //this.canvas.onmousemove = this.moveEvent.bind(this);
            //this.canvas.onmouseup = this.upEvent.bind(this);
            //this.canvas.onmouseout = this.upEvent.bind(this);
            this.moveFlag = false;
            this.upof = {};
            this.radius = 0;
            this.has = [];
            this.startOf = null;
            this.lineMax = 30;
            this.lineMin = 3;
            this.linePressure = 1;
            this.smoothness = 80;
            this.history = [];
        }
        Handwriting.prototype.isCanvasBlank=function(canvas) {
            var blank = document.createElement('canvas');
            blank.width = canvas.width;
            blank.height = canvas.height;
            return canvas.toDataURL() == blank.toDataURL();
        }
        Handwriting.prototype.createImg = function(word) {
            var canvas = this.canvas;
            if(this.isCanvasBlank(canvas)) {
                return;
            }
            var url = canvas.toDataURL({format: 'png', quality: 1});
            hd = hd + 's';
            a = hd;
            res = WordImgUpload(url, word, this.history.length, hd);
            this.clear();
            hd = 'zh-cn';
            console.log(res);
            return res
         }

        Handwriting.prototype.clear = function () {
            this.history = [];
            this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
        }
        Handwriting.prototype.historyBack = function () {
            this.history.pop();
            this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
            for (var i = 0; i < this.history.length; i++) {
                var h = this.history[i];
                for (var j = 0; j < h.length; j+=3) {
                    this.ctx.beginPath();
                    this.ctx.arc(h[j],h[j+1],h[j+2],0,2*Math.PI,true);
                    this.ctx.fill();
                }
            }
        }

        Handwriting.prototype.downEvent = function (e) {
            this.moveFlag = true;
            this.has = [];
            this.history.push([]);
            this.upof = this.getXY(e);
            this.startOf = this.upof;
        }

        Handwriting.prototype.moveEvent = function (e) {
            if (!this.moveFlag)
                return;
            e.preventDefault();
            var of = this.getXY(e);
            var up = this.upof;
            var ur = this.radius;
            this.has.unshift({time:new Date().getTime() ,dis:this.distance(up,of)});
            var dis = 0;
            var time = 0;
            for (var n = 0; n < this.has.length-1; n++) {
                dis += this.has[n].dis;
                time += this.has[n].time-this.has[n+1].time;
                if (dis>this.smoothness)
                    break;
            }
            var or = Math.min(time/dis*this.linePressure+this.lineMin , this.lineMax) / 2;
            this.radius = or;
            this.upof = of;
            if (dis<7)
                return;
            if (this.startOf) {
                up = this.startOf;
                ur = or;
                this.startOf = null;
            }
            var len = Math.ceil(this.distance(up,of)/2);
            for (var i = 0; i < len; i++) {
                var x = up.x + (of.x-up.x)/len*i;
                var y = up.y + (of.y-up.y)/len*i;
                var r = ur + (or-ur)/len*i;
                this.ctx.beginPath();
                this.ctx.arc(x,y,r,0,2*Math.PI,true);
                this.ctx.fill();
                this.history[this.history.length-1].push(x,y,r);
            }
        }

        Handwriting.prototype.upEvent = function (e) {
            this.moveFlag = false;
        }

        Handwriting.prototype.getXY = function (e) {
            var x = e.touches[0].clientX;

            var y = e.touches[0].clientY;
            //var x = e.clientX;
            //var y = e.clientY;
            x = x - this.canvas.offsetLeft + (document.body.scrollLeft || document.documentElement.scrollLeft);
            y = y - this.canvas.offsetTop  + (document.body.scrollTop || document.documentElement.scrollTop);
            hd = hd + parseInt(x, 10) + 'a' + parseInt(y, 10) + 'a' ;
            return {
                x : x,
                y : y
            }
        }

        Handwriting.prototype.distance = function (a,b) {
            var x = b.x-a.x , y = b.y-a.y;
            return Math.sqrt(x*x+y*y);
        }

        var hw = new Handwriting("canvasId");
        hw.lineMax = 7;
        hw.lineMin = 7;
        hw.linePressure = 3.1;
        hw.smoothness = 100;
	})
</script>
<script>
    $('#exit').click(function(){
        //$('.tanchukuang').css("display","none");
        //$('.border_right').css("display","block");
		location.href="boruo.html";

    })
    var fenxiang = $('#fenxiang');
    fenxiang.click(function () {
        $("#mcover").css("display","block");
    })
    $("#mcover").click(
            function(){
                    $("#mcover").css("display","none");  // 点击弹出层，弹出层消失
            }
    )
    document.body.style.overflow='hidden';
    document.documentElement.style.overflow='hidden';

    $("#xian button").click(function () {
        $("#mcover1").css("display","none")
    })
    $("#mcover3").click(function () {
        $("#mcover3").css("display","none");
        $(".border_right").css("display","block");
        $(".tanchukuang").toggle();

    })
</script>


<script>

    function getCookie(name) {
                var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
                if (arr != null) return unescape(arr[2]);
                return null;
            }

            var csrftoken = getCookie('csrftoken');
            var versionId = localStorage.getItem('versionId');
            var msg1 = localStorage.getItem('message');
            var msg2 = JSON.parse(msg1);
            var configData;
            var currentUrl = window.location.href.split('#')[0];
                $.when(

                // 获取config数据
                $.ajax({
                        url: '/fe/user/js_sign',
                        type: 'POST',
                        beforeSend: function(xhr, settings) {
                            xhr.setRequestHeader("X-CSRFToken", csrftoken);
                        },
                        data: {
                            "url": currentUrl,
                        },
                        success: function(data) {
                            configData = data.data;
                        },
                        error: function(xhr, status, error){
                                if (xhr.status == 403 ){
                                    $.ajax({
                                        url: '/fe/user/login',
                                        success: function (data) {
                                            console.log(data);
                                            location.href = data.url;
                                        },
                                        error: function (error) {
                                            console.log('no');
                                            console.log(error);
                                        }
                                    });

                                }
                            }
                    })

                ).then(function() {
                 wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。

                    appId: configData.appid,
                    timestamp: configData.timestamp,
                    nonceStr: configData.noncestr,
                    signature: configData.sign,

                    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage']
                });
                
                var fenxiang = $('#fenxiang');
            fenxiang.click(function (){
              wx.onMenuShareTimeline({
                        title:'修德抄经堂',
                        link:'http://bk-bbe.com/web/front/zhuchao.html',
                        imgUrl: '', // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    })
              var userTranscriptionID = localStorage.getItem('userTranscriptionID');
                var a = 'http://bk-bbe.com/web/front/zhuchao.html?id='+userTranscriptionID+"&vid="+versionId;
              wx.onMenuShareAppMessage({

                title: '修德抄经堂', // 分享标题

                desc: '', // 分享描述

                link: a, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致

                imgUrl: '', // 分享图标

                type: '', // 分享类型,music、video或link，不填默认为link

                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空

                success: function () { 

                    // 用户确认分享后执行的回调函数

                },

                cancel: function () { 

                    // 用户取消分享后执行的回调函数

    }

});
                 });});

</script>


</html>